<?php
/*
 * @Author: 波波
 * @Date: 2025-07-05 
 * @Email: guqule2@yeah.net
 * @LastEditors: 波波
 * @LastEditTime: 2025-07-06 11:47:45
 * @Description: AI 功能
 * @Company: 丸子社区
 */

defined('ABSPATH') || exit;

// 仅在后台文章编辑页面加载脚本
add_action('admin_enqueue_scripts', 'wanzi_ai_admin_scripts');
function wanzi_ai_admin_scripts($hook)
{
    // 仅在文章编辑或新建页面加载
    if ('post.php' != $hook && 'post-new.php' != $hook) {
        return;
    }

    // 检查功能是否开启
    if (!wanzi_option('ai_enable')) {
        return;
    }

    $ajax_vars = array(
        'ajax_url' => admin_url('admin-ajax.php'),
        'content_nonce' => wp_create_nonce('wanzi_ai_nonce')
    );

    wp_enqueue_script('wanzi-admin-ai', get_template_directory_uri() . '/assets/js/admin-ai.js', array('jquery'), THEME_VERSION, true);
    wp_localize_script('wanzi-admin-ai', 'wanzi_ai_ajax', $ajax_vars);
}

// 注册内容生成的 AJAX action
if (wanzi_option('ai_enable')) {
    add_action('wp_ajax_ai_generate_content', 'wanzi_ai_generate_content_callback');
    function wanzi_ai_generate_content_callback()
    {
        check_ajax_referer('wanzi_ai_nonce', 'nonce');

        if (empty($_POST['title'])) {
            wp_send_json_error('标题不能为空。');
        }

        $title = sanitize_text_field($_POST['title']);
        $provider = wanzi_option('ai_provider', 'coze');

        // 调试代码：检查当前获取到的服务商
        if ($provider !== 'coze' && $provider !== 'deepseek') {
            wp_send_json_error('无法识别的 AI 服务商：' . esc_html($provider));
        }

        if ($provider === 'coze') {
            $api_key = wanzi_option('ai_coze_api_key');
            $bot_id = wanzi_option('ai_coze_bot_id');
            $api_base = wanzi_option('ai_coze_api_base', 'com');

            if (empty($api_key) || empty($bot_id)) {
                wp_send_json_error('请在主题设置中配置 Coze Personal Access Token 和 Bot ID。');
            }

            $api_endpoint = 'https://api.coze.' . $api_base . '/open_api/v2/chat';
            
            $user_id = 'user_' . md5(get_current_user_id() . 'wanzi_coze_salt');

            $body = array(
                'bot_id'    => $bot_id,
                'user'      => $user_id,
                'query'     => '请根据以下标题写一篇文章：' . $title,
                'stream'    => false
            );

            $args = array(
                'body'    => json_encode($body),
                'headers' => array(
                    'Content-Type'  => 'application/json',
                    'Authorization' => 'Bearer ' . $api_key,
                ),
                'timeout' => 60,
            );

            $response = wp_remote_post($api_endpoint, $args);

            if (is_wp_error($response)) {
                wp_send_json_error('API 请求失败：' . $response->get_error_message());
            }

            $response_body = wp_remote_retrieve_body($response);
            $data = json_decode($response_body, true);

            if (isset($data['code']) && $data['code'] === 0 && isset($data['messages'])) {
                $content = '';
                foreach ($data['messages'] as $message) {
                    if ($message['type'] === 'answer' && $message['role'] === 'assistant') {
                        $content .= $message['content'];
                    }
                }
                wp_send_json_success($content);
            } else {
                $error_message = '从API返回的数据格式不正确或包含错误。';
                if (isset($data['msg'])) {
                    $error_message = 'API 错误: ' . $data['msg'];
                }
                wp_send_json_error($error_message, $data);
            }
        } elseif ($provider === 'deepseek') {
            $api_key = wanzi_option('ai_deepseek_api_key');

            if (empty($api_key)) {
                wp_send_json_error('请在主题设置中配置 DeepSeek API Key。');
            }

            $api_endpoint = 'https://api.deepseek.com/chat/completions';

            $body = array(
                'model' => 'deepseek-chat',
                'messages' => array(
                    array('role' => 'system', 'content' => '你是一个专业的内容创作者。'),
                    array('role' => 'user', 'content' => '请根据以下标题写一篇公众号文章 返回富文本内容：' . $title)
                ),
                'stream' => false
            );

            $args = array(
                'body'    => json_encode($body),
                'headers' => array(
                    'Content-Type'  => 'application/json',
                    'Authorization' => 'Bearer ' . $api_key,
                ),
                'timeout' => 60,
            );

            $response = wp_remote_post($api_endpoint, $args);

            if (is_wp_error($response)) {
                wp_send_json_error('API 请求失败：' . $response->get_error_message());
            }

            $response_code = wp_remote_retrieve_response_code($response);
            $response_body = wp_remote_retrieve_body($response);
            $data = json_decode($response_body, true);

            if ($response_code === 200 && isset($data['choices'][0]['message']['content'])) {
                $content = $data['choices'][0]['message']['content'];
                wp_send_json_success($content);
            } else {
                $error_message = '未知错误。';
                if (isset($data['error']['message'])) {
                    $error_message = $data['error']['message'];
                } elseif (!empty($response_body)) {
                    $error_message = $response_body;
                }
                wp_send_json_error('API 请求失败: ' . $error_message, $data);
            }
        }
    }
}